//这个文件是对dio的封装
import 'package:dio/dio.dart';

import '../enum/token.dart';
import '../interceptor/DioLogInterceptor.dart';
import '../tools/commons.dart';

class HttpManager {

  //1、通过静态方法 getInstance() 访问实例—————— getInstance() 构造、获取、返回实例
  /*通过工厂方法获取该类的实例，将实例对象按对应的方法返回出去
   *实例不存在时，调用命名构造方法获取一个新的实例 */
  static HttpManager getInstance() {
    _instance ??= HttpManager._internal();
    return _instance!;
  }

  //创建一个 Dio 实例
  late Dio dio;

  //2、静态属性——该类的实例
  static HttpManager? _instance = HttpManager._internal();

  //3、私有的命名构造函数，确保外部不能拿到它————初始化实例
  HttpManager._internal(){
    //4.2、设置BaseOptions
    BaseOptions baseOptions=BaseOptions(
      //基本网址
      baseUrl:"http://localhost:8080/api",
      //连接超时
      connectTimeout: Duration(milliseconds: 30000),
      //接收超时
      receiveTimeout: Duration(milliseconds: 5000),
      //内容类型
      contentType: 'application/json;Charset=UTF-8',
      //响应类型——期待已那种方式接收数据，默认是json
      responseType: ResponseType.json,
    );
    //初始化dio实例
    dio=Dio(baseOptions) ;
    //添加一个拦截器
    dio.interceptors.add(DioLogInterceptor());

  }
  //封装request
  request(String url,{method,option,params,headers}
      ) async {
    Response response;
    try{
      response=await dio.request(url,
          options: Options(
              method: method,
              headers: headers,
          ),
          data: params
      );
      print("response.data:${response.data}");
      print("response.data:${response.statusCode}");
      print("response.data:${response.statusMessage}");
      print("response.data:${response.headers}");
      return response;
    }on Exception catch(e){
      print("请求方法出错:${e.toString()}");
    }
    return null;
  }
  //封装get
  Future<Response?> get(String url,{option,params,headers}) async {
    Response response;
    try{
      response=await dio.get(url,
          options: Options(
              responseType: ResponseType.json,
              headers: headers,
          ),
          data: params
      );
      // print("response.data:${response.data}");
      print("response.data:${response.statusCode}");
      print("response.data:${response.statusMessage}");
      print("response.data:${response.headers}");
      return response;
    }
    on Exception catch(e){
      print("Get方法出错:${e.toString()}");
    }
    return null;
  }

  post(String url,{params}) async {
    Response response;
    //请求参数 为空时，配置
    try{
      response=await dio.post(
        url,
        data:  params,
      );
      print("post response:${response.data}\n");
      return response;
    }
    on Exception catch (e){
      print("post出错:${e.toString()}");
      return null;
    }

  }

}